﻿using System;
using System.Text;
using System.Ext.Xml;
using System.Xml;
using System.Reflection;

namespace mfXmlSerializer
{
    /// <summary>
    /// represents the serialization strategy for simple elements (like string, int, etc.)
    /// </summary>
    public class mfMapSimpleElement : mfMapBaseElement
    {        
        #region CTOR

        public mfMapSimpleElement(mfMapBaseElement baseElement)
            : base(baseElement.Name, baseElement.SetMethod, baseElement.GetMethod, baseElement.ChildMap)
        { }

        #endregion

        #region Methods

        protected override void SerializeElement(XmlWriter xmlWriter, object source)
        {
            //get value on target            
            Object value = GetMethod.Invoke(source, null);
            //TODO: write elementwrite extension method, which can be used by all serialization types to provide null tolerant serialization
            xmlWriter.WriteElementStringIfNotNull(Name, ((value != null) ? value.ToString() : null));
        }

        protected override void DeserializeElement(XmlReader xmlReader, object target)
        {
            xmlReader.Read();
            if (xmlReader.IsNotNodeTextType(this)) return;
            var typedTarget = xmlReader.Value.ConvertToElementType(this);
            SetElement(xmlReader, target, typedTarget);
        }

        protected override void ExecuteSetElement(object target, string newValue)
        {
            var typedTarget = newValue.ConvertToElementType(this);
            SetMethod.Invoke(target, new object[] { typedTarget });
        }

        #endregion
    }
}
